package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;
    public PageResult search(RequestParams Params) {

        try {
            //1准备request
            SearchRequest request = new SearchRequest("hotel");
            //2准备DSL
            //query
            //构建BooleanQuery
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            //获取前端传过来的参数
            String key = Params.getKey();
            if (key==null || "".equals(key)){
                boolQuery.must(QueryBuilders.matchAllQuery());
            }else {
                //查询条件
                boolQuery.must(QueryBuilders.matchQuery("all", key));
            }
            //条件过滤
            //城市条件
            if (Params.getCity()   !=null && !Params.getCity().equals(""))
            {
                //这里用filter是因为不参加算分，不影响性能
                boolQuery.filter(QueryBuilders.termQuery("city",Params.getCity()));
            }
            //品牌条件
            if (Params.getBrand()   !=null && !Params.getBrand().equals(""))
            {
                boolQuery.filter(QueryBuilders.termQuery("brand",Params.getBrand()));
            }
            //星级条件
            if (Params.getStarName() != null && !Params.getStarName().equals("")) {
                boolQuery.filter(QueryBuilders.termQuery("starName", Params.getStarName()));
            }
            //价格条件
            if (Params.getMinPrice() != null && Params.getMaxPrice() != null)
            {
                boolQuery.filter(QueryBuilders.rangeQuery("price")
                        .gte(Params.getMinPrice())
                        .lte(Params.getMaxPrice()));
            }
            //放入source
            request.source().query(boolQuery);
            //分页
            int page = Params.getPage();
            int size = Params.getSize();
            request.source().from((page- 1) * size).size(size);
            //排序
            String location = Params.getLocation();
            if (location != null && location.equals("")) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }
            //3发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应结果
            return handleResponse(response);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private PageResult handleResponse(SearchResponse response)
    {
        //解析响应结果
        SearchHits searchHits = response.getHits();
        //获取总条数
        Long total =  searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        List<HotelDoc> hotels = new ArrayList<>();
        //遍历
        for (SearchHit hit : hits) {
            //获取文档source
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0)
            {
               Object sortValue = sortValues[0];
               hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
        }
        return new PageResult(total,hotels);
    }
}
